import { FormFieldWrapper } from '@components/common/formFieldWrapper/formFieldWrapper'
import { ReactComponentExt } from '@helpers/ReactExt'
import utils from '@helpers/utils'
import { GlobalStoreModel } from '@store/globalStore'
import { BaseProps } from '@store/store'
import { Button, Col, Row } from 'antd'
import Form, { FormComponentProps } from 'antd/lib/form'
import * as moment from 'moment'
import * as React from 'react'
import { formFieldConfig } from './constantConfig'
import * as styles from './createStudentPage.less'

// tslint:disable-next-line:no-empty-interface
export interface CreateStudentPageProps extends BaseProps, FormComponentProps {
  globalStore: GlobalStoreModel
}

// tslint:disable-next-line:no-empty-interface
interface CreateStudentPageState {
  editable: boolean
  sutdentData: ViewModels.CreateStudentData | {}
}

class CreateStudentPage extends ReactComponentExt<CreateStudentPageProps, CreateStudentPageState> {

  public async init() {
    this.state = {
      editable: true,
      sutdentData: {}
    }
    this.handleFormCancel = this.handleFormCancel.bind(this)
    this.handleFormSubmit = this.handleFormSubmit.bind(this)
    const { studentId } = this.query
    if (studentId) {
      await this.getStudentById(studentId)
    }
  }

  public async componentDidMount() {
    // todo
  }

  public render() {
    const { form } = this.props
    const { sutdentData } = this.state
    const { action } = this.query
    return (
      <div className={styles.wrapper}>
        <Form onSubmit={this.handleFormSubmit}>
          <Row gutter={24}>
            <FormFieldWrapper
              data={sutdentData}
              action={action}
              span={12}
              form={form}
              formFieldConfig={formFieldConfig}
            />
          </Row>
          <Row>
            <span className={styles.text}>每一项前面标星号(*)为必填项 </span>
            <Col span={24} style={{ textAlign: 'right' }}>
              <Button onClick={this.handleFormCancel}>取消</Button>
              {
                action === 'look' ? '' :
                  <Button style={{ marginLeft: 8 }} type='primary' htmlType='submit'>{
                    action === 'edit' ? '修改' : '创建'
                  }</Button>
              }
              {/* <a style={{ marginLeft: 8, fontSize: 12 }} onClick={this.toggle}>
                  Collapse <Icon type={this.state.expand ? "up" : "down"} />
                </a> */}
            </Col>
          </Row>
        </Form>
      </div>
    )
  }

  private async getStudentById(studentId: number) {
    const { code, message, data: { student } } = await this.api.getStudentById(studentId)
    if (code !== 0) {
      this.$message.error(message, 5)
      return
    }
    const { joinSchoolTime, name, avatar } = student
    const sutdentData: ViewModels.CreateStudentData = {
      ...student,
      dspJoinSchoolTime: joinSchoolTime ? moment(joinSchoolTime) : null,
      dspAvatarFile: utils.convertToAntdFile(name, [avatar])
    }
    await this.setState({ sutdentData })
  }

  private handleFormSubmit(e: React.MouseEvent) {
    e.stopPropagation()
    e.preventDefault()
    const { form, history } = this.props
    const { action, studentId } = this.query
    form.validateFields(async (err, values: ViewModels.CreateStudentData) => {
      if (err) {
        this.$message.error('请检查学生数据是否完整', 5)
        return
      }
      if (!this.checkFormData(values)) {
        return
      }
      const { dspJoinSchoolTime, dspAvatarFile } = values
      values.joinSchoolTime = moment(dspJoinSchoolTime!).format('YYYY-MM-DD')
      const { status, response, originUrl } = dspAvatarFile[0]
      if (!response && status === 'done') {
        values.avatar = originUrl
      } else {
        values.avatar = dspAvatarFile[0].response!.data.url
      }
      // 保持和后端 Model 一致性
      delete values.dspJoinSchoolTime
      delete values.dspAvatarFile
      if (action === 'edit' && studentId) {
        const { code, message } = await this.api.updateStudentInfo(studentId, values)
        if (code !== 0) {
          this.$message.error(message, 5)
          return
        }
        this.$message.success('创建成功')
      } else {

        const { code, message } = await this.api.createStudent(values)
        if (code !== 0) {
          this.$message.error(message, 5)
          return
        }
        this.$message.success('修改成功')
      }

      history!.push('/student/list')
    })
  }

  private checkFormData(values: PostDataTypes.Student): boolean {
    const { studentNumber, age, fatherName, motherName,
      fatherPhoneNumber, motherPhoneNumber, fatherWechat, motherWxchatNumber } = values
    if (`${studentNumber}`.indexOf('.') > -1) {
      this.$message.error('学生编号不能包含小数点', 5)
      return false
    }

    if (`${age}`.indexOf('.') > -1) {
      this.$message.error('学生年龄不能包含小数点', 5)
      return false
    }

    if (!fatherName && !motherName) {
      this.$message.error('父母名字不能都为空, 必须二者填其一', 5)
      return false
    }

    if (!fatherPhoneNumber && !motherPhoneNumber) {
      this.$message.error('父母手机号不能都为空, 必须二者填其一', 5)
      return false
    }

    if (!fatherWechat && !motherWxchatNumber) {
      this.$message.error('父母微信不能都为空, 必须二者填其一')
      return false
    }

    return true
  }

  private handleFormCancel() {
    const { history } = this.props
    history!.push('/student/list')
  }

}

export default Form.create<CreateStudentPageProps>({ name: 'student_create_form' })(CreateStudentPage)
